import { useState, useCallback, useEffect } from 'react';
import SessionManagerAdapter, { SessionInfo } from '../auth/SessionManagerAdapter';

// 会话管理Hook
export const useSession = () => {
  const [session, setSession] = useState<SessionInfo | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 检查会话状态
  const checkSession = useCallback(() => {
    const currentSession = SessionManagerAdapter.getCurrentSession();
    setSession(currentSession);
    setIsLoading(false);
    return currentSession;
  }, []);

  // 登出
  const logout = useCallback(async () => {
    await SessionManagerAdapter.clearSession();
    setSession(null);
  }, []);

  // 延长会话
  const extendSession = useCallback(async () => {
    const success = await SessionManagerAdapter.extendSession();
    if (success) {
      checkSession(); // 重新检查会话状态
    }
    return success;
  }, [checkSession]);

  // 更新活动时间
  const updateActivity = useCallback(async () => {
    await SessionManagerAdapter.updateActivity();
    checkSession();
  }, [checkSession]);

  // 检查是否需要重新认证
  const needsReauthentication = useCallback(() => {
    return SessionManagerAdapter.needsReauthentication();
  }, []);

  // 获取会话统计
  const getSessionStats = useCallback(() => {
    const stats = SessionManagerAdapter.getSessionStats();
    // 添加剩余时间信息到stats中
    return {
      ...stats,
      timeRemaining: SessionManagerAdapter.formatTimeRemaining()
    };
  }, []);

  // 获取令牌剩余时间
  const getTokenTimeRemaining = useCallback(() => {
    return SessionManagerAdapter.getTokenTimeRemaining();
  }, []);

  // 格式化剩余时间显示
  const formatTimeRemaining = useCallback(() => {
    return SessionManagerAdapter.formatTimeRemaining();
  }, []);

  // 组件挂载时检查会话
  useEffect(() => {
    checkSession();
  }, [checkSession]);

  // 定期更新活动时间（每5分钟）
  useEffect(() => {
    if (session) {
      const interval = setInterval(() => {
        updateActivity();
      }, 5 * 60 * 1000); // 5分钟

      return () => clearInterval(interval);
    }
    return undefined;
  }, [session, updateActivity]);

  return {
    session,
    isLoading,
    isAuthenticated: !!session && SessionManagerAdapter.isSessionValid(),
    checkSession,
    logout,
    extendSession,
    updateActivity,
    needsReauthentication,
    getSessionStats,
    getTokenTimeRemaining,
    formatTimeRemaining
  };
};